package org.example.controller.common;

import cn.dev33.satoken.annotation.SaCheckLogin;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.example.common.fastdfs.service.UploadFileService;
import org.example.common.result.Result;
import org.example.common.utils.SaTokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 通用文件上传
 */
@RestController
@RequestMapping("/file")
@Slf4j
@Tag(name = "文件管理", description = "文件上传下载相关接口，支持多端认证")
@SecurityRequirement(name = "platformBearerAuth")
@SecurityRequirement(name = "enterpriseBearerAuth")
@SecurityRequirement(name = "workbenchBearerAuth")
@SecurityRequirement(name = "personalBearerAuth")
@SecurityRequirement(name = "authorizationBearerAuth")
public class FileController {

    @Autowired
    private UploadFileService uploadFileService;

    @Autowired
    private SaTokenUtils saTokenUtils;

    /**
     * 测试接口
     */
    @GetMapping("/test")
    @Operation(summary = "测试接口", description = "测试文件管理接口是否正常")
    public Result<String> test() {
        // 添加调试信息
        System.out.println("=== 文件管理测试接口 ===");
        System.out.println("当前token: " + saTokenUtils.getTokenValue());
        System.out.println("是否登录: " + saTokenUtils.isLogin());
        System.out.println("当前用户ID: " + saTokenUtils.getCurrentUserId());
        System.out.println("当前用户类型: " + saTokenUtils.getCurrentUserType());
        System.out.println("当前企业ID: " + saTokenUtils.getCurrentCompanyId());
        
        return Result.success("文件管理接口正常");
    }

    /**
     * 公开测试接口（不需要认证）
     */
    @GetMapping("/public-test")
    @Operation(summary = "公开测试接口", description = "测试文件管理接口是否正常，不需要认证")
    public Result<String> publicTest() {
        return Result.success("文件管理公开接口正常");
    }

    // 支持的文件类型
    private static final String[] ALLOWED_EXTENSIONS = {
        "jpg", "jpeg", "png", "gif", "bmp", "webp",  // 图片
        "pdf", "doc", "docx", "xls", "xlsx", "ppt", "pptx",  // 文档
        "txt", "csv", "zip", "rar", "7z"  // 其他
    };

    // 最大文件大小 (100MB)
    private static final long MAX_FILE_SIZE = 100 * 1024 * 1024;


    /**
     * 上传附件（multipart/form-data）
     * form fields: file, attachmentType
     */
    @SaCheckLogin
    @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @Operation(summary = "上传附件", description = "上传通用附件，支持多端认证")
    public Result<Map<String, Object>> upload(@RequestPart("file") MultipartFile file,
                                              @RequestParam(value = "attachmentType", required = false) String attachmentType) {
        try {
            if (file == null || file.isEmpty()) {
                return Result.badRequest("文件不能为空");
            }

            String originalName = file.getOriginalFilename();
            long fileSize = file.getSize();
            String ext = extractExt(originalName);

            // 验证文件大小
            if (fileSize > MAX_FILE_SIZE) {
                return Result.badRequest("文件大小不能超过100MB");
            }

            // 验证文件类型
            if (!isAllowedFileType(ext)) {
                return Result.badRequest("不支持的文件类型: " + ext);
            }

            // 使用FastDFS上传文件
            String fileUrl = uploadToFastDFS(file, ext);

            // 生成文件ID
            String fileId = UUID.randomUUID().toString().replace("-", "");

            Map<String, Object> data = new HashMap<>();
            data.put("id", fileId);
            data.put("fileName", originalName);
            data.put("fileSize", fileSize);
            data.put("fileType", ext);
            data.put("fileUrl", fileUrl);
            data.put("attachmentType", attachmentType);

            log.info("文件上传成功: {} -> {}", originalName, fileUrl);
            return Result.success("上传成功", data);
        } catch (Exception e) {
            log.error("文件上传失败", e);
            return Result.error("上传失败: " + e.getMessage());
        }
    }

    /**
     * 上传到FastDFS
     */
    private String uploadToFastDFS(MultipartFile file, String ext) throws IOException {
        try {
            // 使用真实FastDFS服务上传
            var uploadResult = uploadFileService.upload(file.getOriginalFilename(), file.getInputStream());
            
            log.info("FastDFS上传文件成功: {} -> {}", file.getOriginalFilename(), uploadResult.getUrl());
            
            return uploadResult.getUrl();
        } catch (Exception e) {
            log.error("FastDFS上传失败", e);
            throw new IOException("文件上传到FastDFS失败: " + e.getMessage());
        }
    }

    /**
     * 检查文件类型是否允许
     */
    private boolean isAllowedFileType(String ext) {
        if (ext == null || ext.isEmpty()) {
            return false;
        }
        return Arrays.asList(ALLOWED_EXTENSIONS).contains(ext.toLowerCase());
    }


    /**
     * 提取文件扩展名
     */
    private String extractExt(String name) {
        if (name == null) return "";
        int idx = name.lastIndexOf('.');
        return idx > -1 ? name.substring(idx + 1).toLowerCase() : "";
    }
}


